<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          
          <a-col :md="8" :sm="24">
            <a-form-item label="生产单号">
              <a-input v-model="queryParam.orderNumber" placeholder="请输入生产单号"/>
            </a-form-item>
          </a-col>
          
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons"
                  :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <!--<a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
            </span>
          </a-col>
          
          <a-col :md="24" :sm="24">
            <a-form-item label="归属公司：">
              <FCOrgRadioGroup v-model="queryParam.orgId"
                               :filter-types="[$businessEnum.ORG_TYPE_ENUM.COMPANY.id]"/>
              <!--              <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdCompany">-->
              <!--                <a-radio-button value="">-->
              <!--                  全部-->
              <!--                </a-radio-button>-->
              <!--                <a-radio-button :value="id" v-for="{id, name} in orgs">-->
              <!--                  {{ name }}-->
              <!--                </a-radio-button>-->
              <!--              </a-radio-group>-->
            
            </a-form-item>
          </a-col>
        
        </a-row>
      </a-form>
    </div>
    
    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :alert="true"
      :rowKey="(record) => record.orderId"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >

      <span slot="status" slot-scope="text, record">
           <a-switch v-model:checked="record.status == 0" :loading="record.loading"
                     @change="onOrderStatusChange($event, record)"/>
      </span>
      
      <div :slot="$util.EMS_ORDER_VIEW_STATE.inProgressProductionOrder" slot-scope="text, record">
        <div>
          <a @click="$refs.orderEditForm.disabledShow(record)">详情</a>
          <a-divider type="vertical"/>
          <a @click="$refs.productListModal.show(record)">产品列表</a>
          <a-divider type="vertical"/>
          <a @click="$refs.packingListModal.show(record, '包材列表', 'packingOutReadonly')">包材列表</a>
        </div>
        <div>
          <a @click="$refs.modifyProductModal.show(record)" v-if="hasPerm('emsOrderMaterial:edit')">修改产品</a>
          <a-divider type="vertical" v-if="hasPerm('emsPlanOrder:add')"/>
          <a @click="$refs.reverseExecuteModal.show(record)" v-if="hasPerm('emsPlanOrder:add')">反执行</a>
          <a-divider type="vertical" v-if="hasPerm('emsOrder:endScOrder')"/>
          <a class="text-success hover:text-success" @click="handleCompletedOrder(record)"
             v-if="hasPerm('emsOrder:endScOrder')">完结订单</a>
          <a-divider type="vertical" v-if="hasPerm('emsOrder:delete')"/>
          <a class="text-danger hover:text-danger" @click="handleRemoveOrder(record)"
             v-if="hasPerm('emsOrder:clearDatabaseOrder')">删除订单</a>
        </div>
      </div>
    
    </s-table>
    
    <order-edit-form ref="orderEditForm" @ok="handleOk"/>
    <order-material-index-modal ref="orderMaterialIndexModal" @ok="handleOk"/>
    <product-list-modal ref="productListModal" />
		<!-- @ok="$refs.table.refresh(true)" -->
    <packing-list-modal ref="packingListModal" @ok="handleOk" :readonly="true"/>
    <reverse-execute-modal ref="reverseExecuteModal" @handle-ok="handleOk"/>
    <modify-product-modal ref="modifyProductModal"/>
  
  </a-card>
</template>

<script>
import {STable} from '@/components'
import {getUrlParam} from '@/utils/util'
import FCOrgRadioGroup from '@/components/FcOrgRadioGroup/FCOrgRadioGroup'

import orderEditForm from '@/views/main/emsorder/emsOrderEditForm'
import orderMaterialIndexModal from '@/views/main/emsordermaterial/emsOrderMaterialIndexModal'
import productListModal from './productListModal.vue'
import packingListModal from './packingListModal.vue'
import modifyProductModal from './modifyProductModal.vue'
import reverseExecuteModal from './reverseExecuteModal.vue'
import {endScOrder} from "@/api/modular/main/emsordermaterial/emsOrderMaterialManage.js";
import {del, page} from '@/api/modular/main/emsorder/emsOrderManage.js'

export default {
  components: {
    STable,
    orderEditForm,
    orderMaterialIndexModal,
    packingListModal,
    FCOrgRadioGroup,
    productListModal,
    modifyProductModal,
    reverseExecuteModal,
  },
  data() {
    return {
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      columns: [
        {
          align: 'center',
          
          title: '序号', width: '80px',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          align: 'center',
          
          title: '生产单号',
          dataIndex: 'orderNumber'
        },
        {
          align: 'center',
          
          title: '归属子公司',
          dataIndex: 'targetOrgName'
        },
				{
          align: 'center',
          
          title: '是否海外仓',
          dataIndex: 'isOverseasStore',
					customRender: (text, record, index) => record.isOverseasStore == 'Y' ? '是' : '否'
        },
        {
          align: 'center',
          
          title: '录入时间',
          dataIndex: 'createTime'
        },
        {
          align: 'center',
          
          title: '排单时间',
          dataIndex: 'inProgressTime'
        },
        {
          align: 'center',
          
          title: '操作',
          dataIndex: 'action',
          width: '360px',
          scopedSlots: {customRender: this.$util.EMS_ORDER_VIEW_STATE.inProgressProductionOrder}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      scheduleProductionVisible: false,
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      urlParam: {},
      columnsType: '',
      suppliers: [],
      orgs: [],
      viewState: '',
      materialType: '',
    }
  },
  watch: {
    '$route.path': function (newValue) {
      let urlParam = getUrlParam(this.$route.path)
      this.urlParam = urlParam
      let {orderType, executeStatus, columnsType, viewState, materialType, refCount} = urlParam
      this.columnsType = columnsType
      this.viewState = viewState
      this.materialType = materialType
      this.queryParam = {
        orderType: this.$businessEnum.ORDER_TYPE_ENUM.produceOrder.id,
        executeStatus: executeStatus || ''
      }
      
      
      setTimeout(() => {
        this.$refs.table.refresh(true)
        this.$refs.table.clearSelected()
      }, 100)
    }
  },
  computed: {
    routePath() {
      let urlParam = getUrlParam(this.$route.path)
      return urlParam
    },
    orderType() {
      return this.routePath.orderType
    },
    orderTypeList() {
      let result = []
      result.push({id: '', name: '全部', code: 'all'})
      for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
        let value = this.$businessEnum.ORDER_TYPE_ENUM[key]
        result.push(value)
      }
      return result
    },
    executeStatus() {
      return this.urlParam.executeStatus
    },
    executeStatusList() {
      let result = []
      result.push({id: '', name: '全部', code: 'all'})
      for (const key in this.$businessEnum.EXECUTE_STATUS_ENUM) {
        let value = this.$businessEnum.EXECUTE_STATUS_ENUM[key]
        result.push(value)
      }
      return result
    },
  },
  created() {
    let urlParam = getUrlParam(this.$route.path)
    this.urlParam = urlParam
    let {orderType, executeStatus, columnsType, viewState, materialType, refCount} = urlParam
    this.columnsType = columnsType
    this.viewState = viewState
    this.materialType = materialType
    this.queryParam = {
      orderType: this.$businessEnum.ORDER_TYPE_ENUM.produceOrder.id,
      executeStatus: executeStatus || '',
      refCount
    }
    this.queryParam.refCount = refCount
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleOk() {
      this.$refs.table.refresh()
      this.$refs.table.clearSelected()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 完结订单
    handleCompletedOrder(record) {
      this.$confirm({
        title: '系统提示',
        content: '是否确认完结订单？',
        onOk: () => {
          endScOrder({
            orderId: record.orderId
          }).then(res => {
						// this.$refs.table.refresh()
            if (res.success) {
              this.$message.info('完结订单成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('完结订单失败：' + res.message)
            }
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
      
    },
    // 删除订单
    handleRemoveOrder(record) {
      this.$confirm({
        title: '系统提示',
        content: '是否确认删除订单？',
        onOk: () => {
          del(record).then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('删除失败：' + res.message)
            }
          }).catch((err) => {
            this.$message.error('删除错误：' + err.message)
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
      
    }
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
